<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { Search, Reading, Clock, Tickets, Collection, TrendCharts, Message, Phone, Document, Warning, Location, InfoFilled, ChatDotRound } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/token'
import { ElMessage } from 'element-plus'
import { getUserRecommendations, userLogout, chatWithAI } from '@/api/user'
import { marked } from 'marked'

const router = useRouter()
const userToken = useTokenStore()

// 用户信息
const username = ref(localStorage.getItem('username') || '未登录')
const userAvatar = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')
const searchText = ref('')

// 轮播图数据
const carouselBooks = ref([
  {
    id: 1,
    title: '三体',
    author: '刘慈欣',
    cover: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
  },
  {
    id: 2,
    title: '活着',
    author: '余华',
    cover: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
  },
  {
    id: 3,
    title: '平凡的世界',
    author: '路遥',
    cover: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
  },
  {
    id: 4,
    title: '围城',
    author: '钱钟书',
    cover: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
  },
  {
    id: 5,
    title: '红楼梦',
    author: '曹雪芹',
    cover: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
  }
])

// 修改 quickActions 数据
const quickActions = ref([
  {
    id: 1,
    name: '图书分类',
    icon: Collection,
    description: '浏览全部图书分类',
    path: '/user/categories'
  },
  {
    id: 2,
    name: '借阅历史',
    icon: Clock,
    description: '查看我的借阅记录',
    path: '/user/borrowing-history'
  },
  {
    id: 3,
    name: '热度排行',
    icon: TrendCharts,
    description: '最受欢迎的图书',
    path: '/user/ranking'
  },
  {
    id: 4,
    name: '我的收藏',
    icon: Reading,
    description: '收藏图书列表',
    path: '/user/favorites'
  },
  {
    id: 5,
    name: '预约记录',
    icon: Tickets,
    description: '查看预约状态',
    path: '/user/reservations'
  }
])

// 修改推荐书籍的接口定义
interface RecommendedBook {
  bookId: number
  title: string
  author: string
  coverImage: string
  description: string
}

// 修改推荐书籍数据的类型
const recommendedBooks = ref<RecommendedBook[]>([])

// 获取推荐书籍的方法
const getRecommendedBooks = async () => {
  try {
    const res = await getUserRecommendations()
    recommendedBooks.value = res.data
  } catch (error) {
    ElMessage.error('获取推荐书籍失败')
  }
}

// 修改AI对话相关的数据和方法
const chatInput = ref('')
const chatMessages = ref([{
  type: 'ai',
  content: '你好！我是你的图书助手，有什么可以帮你的吗？'
}])
const chatLoading = ref(false)

// 添加消息容器的ref
const chatMessagesRef = ref(null)

// 添加滚动到底部的方法
const scrollToBottom = () => {
  if (chatMessagesRef.value) {
    const container = chatMessagesRef.value
    container.scrollTop = container.scrollHeight
  }
}

// 监听路由变化
const handleRouteChange = () => {
  if (chatMessages.value.length > 1) { // 如果有对话记录（不只是欢迎消息）
    sessionStorage.setItem('tempChatMessages', JSON.stringify(chatMessages.value))
  }
}

// 在组件挂载时检查是否有临时保存的对话记录
onMounted(() => {
  getRecommendedBooks()
  const tempMessages = sessionStorage.getItem('tempChatMessages')
  if (tempMessages) {
    chatMessages.value = JSON.parse(tempMessages)
    nextTick(() => {
      scrollToBottom() // 在消息加载后滚动到底部
    })
  }
})

// 在组件卸载时清除临时保存的对话记录
onUnmounted(() => {
  sessionStorage.removeItem('tempChatMessages')
})

// 修改handleSendMessage函数，在更新消息后滚动到底部
const handleSendMessage = async () => {
  if (!chatInput.value.trim()) {
    ElMessage.warning('请输入消息内容')
    return
  }
  
  // 添加用户消息
  const userMessage = chatInput.value.trim()
  chatMessages.value.push({
    type: 'user',
    content: userMessage
  })
  scrollToBottom() // 滚动到底部
  
  // 清空输入框
  chatInput.value = ''
  
  // 添加AI消息占位
  const aiMessageIndex = chatMessages.value.length
  chatMessages.value.push({
    type: 'ai',
    content: ''
  })
  scrollToBottom() // 滚动到底部
  
  chatLoading.value = true
  let buffer = ''
  let fullResponse = ''
  
  try {
    const stream = await chatWithAI(userMessage)
    
    while (true) {
      const { value, done } = await stream.reader.read()
      if (done) break
      
      // 将新数据添加到缓冲区
      buffer += stream.decoder.decode(value, { stream: true })
      
      // 查找完整的数据行
      let newlineIndex
      while ((newlineIndex = buffer.indexOf('\n')) !== -1) {
        const line = buffer.slice(0, newlineIndex)
        buffer = buffer.slice(newlineIndex + 1)
        
        if (line.startsWith('data:')) {
          const content = line.slice(5).trim()
          if (content) {
            fullResponse += content
            // 更新AI回复内容，处理格式
            if (aiMessageIndex < chatMessages.value.length) {
              // 处理引号和格式
              let processedContent = fullResponse
                .replace(/"{2,}/g, '"')
                .replace(/^"|"$/g, '')
                .replace(/"([^"]*?)"/g, '$1')
                .replace(/\n{3,}/g, '\n\n')
                .replace(/\s+/g, ' ')
                .replace(/\[\s+/g, '[')
                .replace(/\s+\]/g, ']')
                .replace(/\(\s+/g, '(')
                .replace(/\s+\)/g, ')')
                .replace(/\\n/g, '\n')
                .replace(/\n\s+/g, '\n')
                .replace(/\s+\n/g, '\n')
                .trim()

              chatMessages.value[aiMessageIndex].content = processedContent
              scrollToBottom() // 滚动到底部
            }
          }
        }
      }
    }
    
    // 处理缓冲区中剩余的数据
    if (buffer.length > 0 && buffer.startsWith('data:')) {
      const content = buffer.slice(5).trim()
      if (content) {
        fullResponse += content
        if (aiMessageIndex < chatMessages.value.length) {
          let processedContent = fullResponse
            .replace(/"{2,}/g, '"')
            .replace(/^"|"$/g, '')
            .replace(/"([^"]*?)"/g, '$1')
            .replace(/\n{3,}/g, '\n\n')
            .replace(/\s+/g, ' ')
            .replace(/\[\s+/g, '[')
            .replace(/\s+\]/g, ']')
            .replace(/\(\s+/g, '(')
            .replace(/\s+\)/g, ')')
            .replace(/\\n/g, '\n')
            .replace(/\n\s+/g, '\n')
            .replace(/\s+\n/g, '\n')
            .trim()

          chatMessages.value[aiMessageIndex].content = processedContent
          scrollToBottom() // 滚动到底部
        }
      }
    }
  } catch (error) {
    console.error('AI对话出错:', error)
    ElMessage.error('对话失败，请重试')
    // 移除失败的消息
    if (aiMessageIndex < chatMessages.value.length) {
      chatMessages.value.splice(aiMessageIndex, 1)
      scrollToBottom() // 滚动到底部
    }
  } finally {
    chatLoading.value = false
  }
}

// 监听路由变化
watch(() => router.currentRoute.value.path, handleRouteChange)

// 点击事件处理函数
const handleLogoClick = () => {
  // 处理Logo点击，通常返回首页
}

const handleSearch = () => {
  if (!searchText.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  console.log('搜索关键词:', searchText.value.trim())
  router.push({
    path: '/user/search-results',
    query: { keyword: searchText.value.trim() }
  }).catch(err => {
    console.error('路由跳转失败:', err)
    ElMessage.error('搜索跳转失败，请重试')
  })
  // 清空搜索框
  searchText.value = ''
}

const handleUserCommand = async (command: string) => {
  switch (command) {
    case 'profile':
      router.push('/user/profile')
      break
    case 'settings':
      router.push('/user/settings')
      break
    case 'logout':
      try {
        await userLogout()
        userToken.removeToken()
        localStorage.removeItem('username')
        ElMessage.success('退出登录成功')
        router.push('/')
      } catch (error) {
        ElMessage.error('退出登录失败，请重试')
      }
      break
  }
}

const handleCarouselClick = (book: any) => {
  // 处理轮播图点击，通常跳转到书籍详情
}

const handleActionClick = (action: any) => {
  router.push(action.path)
}

const handleBookClick = (book: RecommendedBook) => {
  router.push({
    path: '/user/book-detail',
    query: { id: book.bookId }
  })
}

const handleFooterLink = (type: string) => {
  // 处理页脚链接点击
  switch (type) {
    case 'guide':
      // 处理使用指南
      break
    case 'rules':
      // 处理借阅规则
      break
    case 'map':
      // 处理网点地图
      break
    case 'about':
      // 处理关于我们
      break
  }
}

// 修改markdown渲染函数
const renderMarkdown = (text) => {
  // 配置marked选项
  marked.setOptions({
    breaks: true, // 支持GitHub风格的换行
    gfm: true, // 启用GitHub风格的Markdown
  })
  return marked(text)
}

// 添加清空对话记录的方法
const clearChatHistory = () => {
  chatMessages.value = [{
    type: 'ai',
    content: '你好！我是你的图书助手，有什么可以帮你的吗？'
  }]
  sessionStorage.removeItem('tempChatMessages')
}
</script>

<template>
  <div class="book-user-container">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-left">
        <div class="logo" @click="handleLogoClick">
          <img src="https://lovechronicle.oss-cn-zhangjiakou.aliyuncs.com/book.jpg" alt="Library Logo" class="logo-img">
          <span class="logo-text">图书借阅系统</span>
        </div>
      </div>

      <div class="header-center">
        <el-input
          v-model="searchText"
          placeholder="搜索图书..."
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </div>

      <div class="header-right">
        <el-dropdown @command="handleUserCommand" trigger="hover">
          <span class="user-info">
            <el-avatar :size="40" :src="userAvatar" />
            <span class="username">{{ username }}</span>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人中心</el-dropdown-item>
              <el-dropdown-item command="settings">设置</el-dropdown-item>
              <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <!-- 路由视图 -->
    <router-view v-slot="{ Component }">
      <transition name="fade" mode="out-in">
        <component :is="Component" />
      </transition>
    </router-view>

    <!-- 当在搜索结果页面时隐藏以下内容 -->
    <template v-if="!$route.path.includes('search-results')">
      <!-- 轮播图区域 -->
      <div class="carousel-section">
        <el-carousel height="400px" :interval="4000">
          <el-carousel-item v-for="item in carouselBooks" :key="item.id" @click="handleCarouselClick(item)">
            <div class="carousel-content">
              <div class="carousel-image" :style="{ backgroundImage: `url(${item.cover})` }">
                <div class="carousel-overlay">
                  <h2>{{ item.title }}</h2>
                  <p>{{ item.author }}</p>
                </div>
              </div>
            </div>
          </el-carousel-item>
        </el-carousel>
      </div>

      <!-- 图书分类区域 -->
      <div class="category-section">
        <el-row :gutter="30" justify="center">
          <el-col :xs="12" :sm="8" :md="6" :lg="4" v-for="action in quickActions" :key="action.id" @click="handleActionClick(action)">
            <el-card class="action-card" shadow="hover">
              <div class="action-icon">
                <el-icon><component :is="action.icon" /></el-icon>
              </div>
              <span class="action-text">{{ action.name }}</span>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- AI 对话区域 -->
      <div class="ai-chat-section">
        <div class="ai-chat-container">
          <div class="ai-chat-header">
            <el-icon><ChatDotRound /></el-icon>
            <span>智能图书助手</span>
          </div>
          <div class="ai-chat-messages" ref="chatMessagesRef">
            <div v-for="(message, index) in chatMessages" 
                 :key="index" 
                 :class="['message', message.type]">
              <div class="message-content" v-if="message.type === 'user'">{{ message.content }}</div>
              <div class="message-content markdown-content" v-else v-html="renderMarkdown(message.content)"></div>
            </div>
            <div v-if="chatLoading" class="message ai">
              <div class="message-content">
                <el-icon class="loading"><svg viewBox="0 0 1024 1024" class="loading-icon"><path d="M512 1024c-69.1 0-136.2-13.5-199.3-40.2C251.7 958 197 921 150 874c-47-47-84-101.7-109.8-162.7C13.5 648.2 0 581.1 0 512c0-19.9 16.1-36 36-36s36 16.1 36 36c0 59.4 11.6 117 34.6 171.3c22.2 52.4 53.9 99.5 94.3 139.9c40.4 40.4 87.5 72.2 139.9 94.3C395 940.4 452.6 952 512 952c59.4 0 117-11.6 171.3-34.6c52.4-22.2 99.5-53.9 139.9-94.3c40.4-40.4 72.2-87.5 94.3-139.9C940.4 629 952 571.4 952 512c0-59.4-11.6-117-34.6-171.3c-22.2-52.4-53.9-99.5-94.3-139.9c-40.4-40.4-87.5-72.2-139.9-94.3C629 83.6 571.4 72 512 72c-19.9 0-36-16.1-36-36s16.1-36 36-36c69.1 0 136.2 13.5 199.3 40.2C772.3 66 827 103 874 150c47 47 84 101.7 109.8 162.7C1010.5 375.8 1024 442.9 1024 512c0 69.1-13.5 136.2-40.2 199.3C958 772.3 921 827 874 874c-47 47-101.7 84-162.7 109.8C648.2 1010.5 581.1 1024 512 1024z"></path></svg></el-icon>
              </div>
            </div>
          </div>
          <div class="ai-chat-input">
            <el-input
              v-model="chatInput"
              placeholder="输入你的问题..."
              :suffix-icon="Message"
              @keyup.enter="handleSendMessage"
            >
              <template #append>
                <el-button @click="handleSendMessage">发送</el-button>
              </template>
            </el-input>
          </div>
        </div>
      </div>

      <!-- 推荐书籍区域 -->
      <div class="recommended-section">
        <h2 class="section-title">推荐图书</h2>
        <el-row :gutter="30">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="book in recommendedBooks" :key="book.bookId" @click="handleBookClick(book)">
            <el-card class="book-card" shadow="hover">
              <div class="book-cover-wrapper">
                <img :src="book.coverImage" class="book-cover" />
              </div>
              <div class="book-info">
                <h3 class="book-title">{{ book.title }}</h3>
                <p class="author">{{ book.author }}</p>
                <p class="description">{{ book.description }}</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 页脚 -->
      <el-footer class="footer">
        <div class="footer-content">
          <div class="footer-section">
            <h3>关于我们</h3>
            <p>图书借阅系统致力于为广大读者提供优质的阅读体验</p>
            <div class="contact-info">
              <p><el-icon><Message /></el-icon> contact@library.com</p>
              <p><el-icon><Phone /></el-icon> 123-456-7890</p>
            </div>
          </div>
          <div class="footer-section">
            <h3>快速链接</h3>
            <ul class="footer-links">
              <li @click="handleFooterLink('guide')"><el-icon><Document /></el-icon> 使用指南</li>
              <li @click="handleFooterLink('rules')"><el-icon><Warning /></el-icon> 借阅规则</li>
              <li @click="handleFooterLink('map')"><el-icon><Location /></el-icon> 网点地图</li>
              <li @click="handleFooterLink('about')"><el-icon><InfoFilled /></el-icon> 关于我们</li>
            </ul>
          </div>
          <div class="footer-section">
            <h3>服务时间</h3>
            <div class="service-time">
              <p>周一至周五：9:00 - 21:00</p>
              <p>周六至周日：10:00 - 18:00</p>
            </div>
          </div>
        </div>
        <div class="footer-bottom">
          <p class="copyright">© 2024 图书借阅系统 All Rights Reserved.</p>
        </div>
      </el-footer>
    </template>
  </div>
</template>

<style scoped>
.book-user-container {
  background-color: #f9f6f2;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 70px !important;
}

.header-left {
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  gap: 15px;
}

.logo-img {
  width: 50px;
  height: 50px;
  object-fit: contain;
}

.logo-text {
  font-size: 26px;
  font-weight: 600;
  color: #2c3e50;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
}

.header-center {
  width: 450px;
}

.header-center :deep(.el-input__wrapper) {
  height: 40px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.user-info:hover {
  background-color: transparent;
}

.username {
  font-size: 16px;
  color: #333;
}

.carousel-section {
  margin: 20px auto;
  max-width: 1200px;
}

.carousel-content {
  height: 100%;
  width: 100%;
}

.carousel-image {
  height: 100%;
  width: 100%;
  background-size: cover;
  background-position: center;
  position: relative;
}

.carousel-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  color: white;
  padding: 40px;
}

.carousel-overlay h2 {
  font-size: 32px;
  margin-bottom: 10px;
  font-weight: bold;
}

.carousel-overlay p {
  font-size: 18px;
  opacity: 0.9;
}

/* 修改轮播图指示器样式 */
:deep(.el-carousel__indicators) {
  bottom: 20px;
}

:deep(.el-carousel__indicator) {
  padding: 0 4px;
}

:deep(.el-carousel__button) {
  width: 30px;
  height: 3px;
  border-radius: 3px;
  background-color: rgba(255, 255, 255, 0.7);
}

:deep(.el-carousel__indicator.is-active .el-carousel__button) {
  background-color: white;
}

.category-section {
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 40px;
}

.action-card {
  padding: 16px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  height: 110px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 10px;
  border: none;
  background: linear-gradient(145deg, #ffffff, #f5f5f5);
  border-radius: 15px;
  margin: 0 auto;
  max-width: 200px;
}

.action-card:hover {
  transform: translateY(-5px);
  background: linear-gradient(145deg, #f5f5f5, #ffffff);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
}

.action-icon {
  background: var(--el-color-primary-light-9);
  padding: 16px;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.action-card:hover .action-icon {
  background: var(--el-color-primary);
  color: white;
}

.action-icon .el-icon {
  font-size: 24px;
  color: var(--el-color-primary);
  transition: all 0.3s ease;
}

.action-card:hover .action-icon .el-icon {
  color: white;
}

.action-text {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.recommended-section {
  max-width: 1200px;
  margin: 40px auto;
  padding: 0 20px;
}

.section-title {
  margin-bottom: 30px;
  font-size: 28px;
  font-weight: bold;
  text-align: center;
  color: #2c3e50;
}

.book-card {
  margin-bottom: 30px;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  height: 460px;
  display: flex;
  flex-direction: column;
}

.book-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.book-cover-wrapper {
  height: 360px;
  overflow: hidden;
  position: relative;
  flex-shrink: 0;
}

.book-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.book-card:hover .book-cover {
  transform: scale(1.05);
}

.book-info {
  padding: 12px 15px;
  height: 100px;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.book-title {
  font-size: 16px;
  font-weight: bold;
  color: #2c3e50;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.2;
  margin: 0 0 6px 0;
}

.author {
  font-size: 14px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.2;
  margin: 0 0 6px 0;
}

.description {
  font-size: 13px;
  color: #666;
  line-height: 1.2;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin: 0;
}

.footer {
  background: #2c3e50;
  padding: 60px 0 20px;
  color: #fff;
  margin-top: 80px;
  height: auto !important;
}

.footer-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  gap: 40px;
  flex-wrap: wrap;
}

.footer-section {
  flex: 1;
  min-width: 250px;
}

.footer-section h3 {
  font-size: 20px;
  margin-bottom: 20px;
  color: #ffffff;
  position: relative;
  font-weight: 600;
}

.footer-section h3::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: -8px;
  width: 40px;
  height: 3px;
  background: #409eff;
}

.contact-info p {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  color: #ecf0f1;
}

.footer-links {
  list-style: none;
  padding: 0;
}

.footer-links li {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  color: #ecf0f1;
  cursor: pointer;
  transition: color 0.3s;
}

.footer-links li:hover {
  color: #409eff;
}

.service-time p {
  margin-bottom: 12px;
  color: #ecf0f1;
}

.footer-bottom {
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.copyright {
  text-align: center;
  color: #bdc3c7;
  font-size: 14px;
}

/* 添加图标样式 */
.el-icon {
  vertical-align: middle;
}

/* 修改下拉菜单样式 */
:deep(.el-dropdown-menu) {
  padding: 4px 0;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-dropdown-menu__item) {
  padding: 8px 20px;
  font-size: 14px;
  line-height: 1.5;
}

:deep(.el-dropdown-menu__item:hover) {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

/* 添加过渡动画样式 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* AI 对话栏样式 */
.ai-chat-section {
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 40px;
}

.ai-chat-container {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.ai-chat-header {
  background: linear-gradient(135deg, #b8a7ca, #d4c1e0);
  color: white;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
}

.ai-chat-messages {
  height: 300px;
  overflow-y: auto;
  padding: 16px;
  background: #f9f9f9;
}

.message {
  margin-bottom: 4px;
  display: flex;
  flex-direction: column;
}

.message.user {
  align-items: flex-end;
}

.message.ai {
  align-items: flex-start;
}

.message-content {
  max-width: 80%;
  padding: 6px 10px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.3;
  position: relative;
  white-space: pre-line;
  word-break: break-word;
}

.message.user .message-content {
  background: #b8a7ca;
  color: white;
  border-radius: 12px 12px 0 12px;
}

.message.ai .message-content {
  background: white;
  color: #333;
  border-radius: 12px 12px 12px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e8e0ee;
}

.ai-chat-input {
  padding: 12px;
  background: white;
  border-top: 1px solid #e8e0ee;
}

.ai-chat-input :deep(.el-input__wrapper) {
  box-shadow: none;
  border: 1px solid #d4c1e0;
}

.ai-chat-input :deep(.el-input__wrapper:hover) {
  border-color: #b8a7ca;
}

.loading-icon {
  animation: rotate 1s linear infinite;
  width: 20px;
  height: 20px;
  fill: #b8a7ca;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 修改Markdown内容样式 */
.markdown-content {
  white-space: pre-line;
  word-break: break-word;
}

.markdown-content :deep(p) {
  margin: 0;
  line-height: 1.3;
}

.markdown-content :deep(strong) {
  font-weight: 600;
  color: #333;
}

.markdown-content :deep(ul), 
.markdown-content :deep(ol) {
  margin: 0;
  padding-left: 16px;
}

.markdown-content :deep(li) {
  margin: 0;
  line-height: 1.3;
}

.markdown-content :deep(a) {
  color: #b8a7ca;
  text-decoration: none;
  word-break: break-all;
}

.markdown-content :deep(a:hover) {
  text-decoration: underline;
}

.markdown-content :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 8px 0;
}

.message-content {
  max-width: 80%;
  padding: 12px 16px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.6;
  position: relative;
  white-space: pre-line;
  word-break: break-word;
}
</style>
